#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "mythread.h"
#include <QThreadPool>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 1. 创建任务类对象
    Generate* gen = new Generate;
    connect(this, &MainWindow::starting, gen, &Generate::recvNum);

    BubbleSort* bubble = new BubbleSort;
    connect(gen, &Generate::sendArray, bubble, &BubbleSort::recvArray);

    QuickSort* quick = new QuickSort;
    connect(gen, &Generate::sendArray, quick, &QuickSort::recvArray);

    // 2. 启动子线程
    connect(ui->start, &QPushButton::clicked, this, [=]()
    {
        qDebug() << "Start Generate nums...";
        ui->randList->clear();
        ui->bubbleList->clear();
        ui->quickList->clear();

        emit starting(10000);
        QThreadPool::globalInstance()->start(gen);
    });

    // 3. 接受子线程发送的数据
    connect(gen, &Generate::sendArray, this, [=](QVector<int> list)
    {
        QThreadPool::globalInstance()->start(bubble);
        QThreadPool::globalInstance()->start(quick);
        for(int i = 0; i < list.size(); ++i)
        {
            ui->randList->addItem(QString::number(list.at(i)));
        }
    });

    // 4. 显示排序结果
    connect(bubble, &BubbleSort::finish, this, [=](QVector<int> list)
    {
        for(int i = 0; i < list.size(); ++i)
        {
            ui->bubbleList->addItem(QString::number(list.at(i)));
        }
    });
    connect(quick, &QuickSort::finish, this, [=](QVector<int> list)
    {
        for(int i = 0; i < list.size(); ++i)
        {
            ui->quickList->addItem(QString::number(list.at(i)));
        }
    });

    connect(this, &MainWindow::destroyed, this, [=]()
    {
        gen->deleteLater();
        bubble->deleteLater();
        quick->deleteLater();
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}

